<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>添加盘点单</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="计划日期" prop="plannedDate">
              <el-date-picker
                v-model="form.plannedDate"
                type="datetime"
                placeholder="请选择计划日期"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled-date="disabledDate"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点人" prop="inventoryUser">
              <el-select v-model="form.inventoryUser" placeholder="请选择盘点人" style="width: 100%" filterable :disabled="true">
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.nickName"
                  :value="user.nickName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备件仓库" prop="warehouseCode">
              <el-select 
                v-model="form.warehouseCode" 
                placeholder="请选择备件仓库" 
                style="width: 100%" 
                filterable
                clearable
                @change="onWarehouseChange"
              >
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.warehouseCode || w.code || w.value"
                  :label="w.warehouseName || w.name || w.label"
                  :value="w.warehouseCode || w.code || w.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备件选择 -->
        <div style="margin: 20px 0; font-weight: 600;">备件信息</div>
        <div style="margin-bottom: 10px; text-align: right;">
          <el-button
            type="primary"
            size="small"
            @click="showPartSelector = true"
            :disabled="!form.warehouseCode"
          >
            选择备件
          </el-button>
        </div>
        <el-table :data="selectedParts" size="mini" border>
          <el-table-column label="备件编号" prop="partNo" width="120" />
          <el-table-column label="备件名称" prop="partName" width="180" />
          <el-table-column label="规格型号" prop="specNo" width="120" />
          <el-table-column label="备件类型" prop="partTypeCode">
            <template slot-scope="scope">
              <span>{{ getPartTypeName(scope.row.partTypeCode) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="stockTotal" width="100">
            <template slot-scope="scope">
              <span>{{ Math.floor(scope.row.stockTotal || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" v-if="selectedParts && selectedParts.length > 0">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="removePart(scope.row.partNo)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="$router.back()">返 回</el-button>
          <el-button type="primary" @click="handleSubmit">提 交</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 备件选择器 -->
    <PartSelector
      :visible.sync="showPartSelector"
      :warehouse-code="form.warehouseCode"
      @confirm="handlePartSelect"
      @cancel="showPartSelector = false"
    />
  </div>
</template>

<script>
import PartSelector from '../components/PartSelector.vue'
import { addInventory } from '@/api/inventory/inventory'
import { loadInventoryDictionaries } from '@/utils/dictionary'

export default {
  name: 'InventoryFormPage',
  components: { PartSelector },
  data() {
    // 计划日期校验规则
    const validatePlannedDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择计划日期'));
      } else {
        const selectedDate = new Date(value);
        const today = new Date();
        // 将时间部分设置为0，只比较日期部分
        selectedDate.setHours(0, 0, 0, 0);
        today.setHours(0, 0, 0, 0);

        if (selectedDate < today) {
          callback(new Error('计划日期不能早于今天'));
        } else {
          callback();
        }
      }
    };

    return {
      showPartSelector: false,
      selectedParts: [],
      warehouseOptions: [],
      userOptions: [],
      partTypeOptions: [],
      pickerOptions: {
        disabledDate: (time) => {
          // 禁用今天的之前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          return time.getTime() < today.getTime();
        }
      },
      form: {
        plannedDate: null,
        inventoryUser: null,
        warehouseCode: null,
        remark: null
      },
      rules: {
        plannedDate: [
          { required: true, message: '请选择计划日期', trigger: 'change' },
          { validator: validatePlannedDate, trigger: 'change' }
        ],
        inventoryUser: [{ required: true, message: '请选择盘点人', trigger: 'change' }],
        warehouseCode: [{ required: true, message: '请选择备件仓库', trigger: 'change' }]
      }
    }
  },
  async created() {
    // 统一加载所有字典数据（仓库和备件类型）
    await this.loadAllDictionaries()
    this.setCurrentUserAsInventoryUser()
  },
  methods: {
    // 禁用过去的日期（保留此方法以确保向后兼容）
    disabledDate(time) {
      // 只比较日期部分，不禁用今天
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return time.getTime() < today.getTime();
    },

    // 统一加载所有字典数据
    async loadAllDictionaries() {
      try {
        // 使用统一的字典加载器加载所有盘点相关数据
        const dictionaries = await loadInventoryDictionaries()
        
        // 设置所有字典数据
        this.warehouseOptions = dictionaries.warehouses || []
        this.partTypeOptions = dictionaries.partTypes || []
        
        // 如果仓库数据为空，尝试直接从API加载
        if (!this.warehouseOptions || this.warehouseOptions.length === 0) {
          await this.loadWarehousesDirectly()
        }
      } catch (error) {
        console.error('加载字典数据失败:', error)
        // 设置默认空数组，避免undefined错误
        this.warehouseOptions = []
        this.partTypeOptions = []
        // 尝试直接从API加载仓库数据
        await this.loadWarehousesDirectly()
      }
    },
    
    // 直接从API加载仓库数据作为备用方式
    async loadWarehousesDirectly() {
      try {
        const request = require('@/utils/request')
        
        // 尝试多个可能的API端点
        const endpoints = [
          '/system/warehouse/list',
          '/inventory/warehouse/list',
          '/warehouse/list'
        ]
        
        for (const endpoint of endpoints) {
          try {
            const response = await request({
              url: endpoint,
              method: 'get',
              params: { pageNum: 1, pageSize: 9999, enabled: 1 }
            })
            
            // 处理不同可能的数据结构
            let warehouses = []
            if (response.rows && Array.isArray(response.rows)) {
              warehouses = response.rows
            } else if (response.data && Array.isArray(response.data)) {
              warehouses = response.data
            }
            
            if (warehouses.length > 0) {
              // 标准化仓库数据格式
              this.warehouseOptions = warehouses.map(w => ({
                warehouseCode: w.code || w.warehouseCode || w.value,
                warehouseName: w.name || w.warehouseName || w.label
              }))
              this.$message.success('仓库数据加载成功')
              return
            }
          } catch (endpointError) {
            console.warn(`尝试API ${endpoint} 失败:`, endpointError)
            // 继续尝试下一个端点
          }
        }
        
        // 如果所有API都失败，提供模拟数据作为最后的备用
        this.provideMockWarehouseData()
      } catch (error) {
        console.error('备用方式加载仓库数据失败:', error)
        // 提供模拟数据
        this.provideMockWarehouseData()
      }
    },
    
    // 提供模拟仓库数据作为最后的备用方案
    provideMockWarehouseData() {
      this.warehouseOptions = [
        { warehouseCode: 'WAREHOUSE_001', warehouseName: '主仓库' },
        { warehouseCode: 'WAREHOUSE_002', warehouseName: '备用仓库' },
        { warehouseCode: 'WAREHOUSE_003', warehouseName: '工具仓库' }
      ]
      this.$message.warning('使用模拟仓库数据，请联系管理员配置真实仓库')
    },
    
    // 当仓库选择变化时的处理函数
    onWarehouseChange(value) {
      console.log('选择的仓库:', value)
      // 清除已选择的备件，确保选择新仓库后重新选择备件
      if (value && this.selectedParts.length > 0) {
        this.$confirm('切换仓库将清除已选择的备件，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.selectedParts = []
        }).catch(() => {
          // 用户取消，恢复之前的选择
          // 注意：这里可能需要额外逻辑来恢复之前的值
        })
      }
    },
    // 将当前登录用户作为盘点人
    setCurrentUserAsInventoryUser() {
      try {
        const getters = (this.$store && this.$store.getters) || {}
        const name = getters.nickName || getters.name || getters.userName || ''
        const id = getters.id || getters.userId || 0
        this.userOptions = name ? [{ userId: id, nickName: name }] : []
        this.form.inventoryUser = name
        this.$userLoaded = true
      } catch (e) {
        this.userOptions = []
        this.form.inventoryUser = ''
      }
    },
    // 处理备件选择确认
    handlePartSelect(parts) {
      // 合并新选择的备件，避免重复
      const existingPartNos = this.selectedParts.map(p => p.partNo)
      const newParts = parts.filter(p => !existingPartNos.includes(p.partNo))
      this.selectedParts = [...this.selectedParts, ...newParts]
      this.showPartSelector = false
    },
    // 移除备件
    removePart(partNo) {
      this.selectedParts = this.selectedParts.filter(p => p.partNo !== partNo)
    },
    /** 获取备件类型名称 */
    getPartTypeName(code) {
      if (!code) return '';
      const partType = this.partTypeOptions.find(type => type.code === code);
      return partType ? partType.name : code;
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return

        if (this.selectedParts.length === 0) {
          this.$message.warning('请至少选择一个备件')
          return
        }

        const payload = {
          ...this.form,
          partList: this.selectedParts.map(part => ({
            partNo: part.partNo,
            partName: part.partName,
            specNo: part.specNo,
            partTypeCode: part.partTypeCode,
            theoreticalQty: Math.floor(part.stockTotal || 0)
          }))
        }

        addInventory(payload).then(() => {
          this.$message.success('添加成功')
          // 延迟一下确保消息显示，然后关闭当前标签页并返回到盘点列表
          setTimeout(() => {
            // 关闭当前标签页
            this.$store.dispatch('tagsView/delView', this.$route)
            // 返回到之前的页面
            this.$router.back()
          }, 500)
        }).catch(error => {
          console.error('提交失败:', error)
          this.$message.error('添加失败')
        })
      })
    }
  }
}
</script>

<style scoped>
.info-section {
  margin-bottom: 20px;
}

.info-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}
</style>